//
//  QRCodeViewCtr.swift
//  SwiftStory
//
//  Created by ZxjMacBookPro on 2020/4/19.
//  Copyright © 2020 ZxjMacBookPro. All rights reserved.
//

import UIKit
import AVFoundation

class QRCodeViewCtr: UIViewController {

    @IBOutlet weak var scanLineTop: NSLayoutConstraint!
    @IBOutlet weak var containerHeight: NSLayoutConstraint!
    @IBOutlet weak var scanLineView: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "扫一扫"
        
        setupNav()
        
        scanQRCode()
        // Do any additional setup after loading the view.
    }

    private func setupNav(){
        let rightBtn = UIButton()
        rightBtn.setTitle("相册", for: .normal)
        rightBtn.addTarget(self, action: #selector(rightBtnClick), for: .touchUpInside)
        rightBtn.sizeToFit()
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightBtn)
        
        navigationController?.navigationBar.barTintColor = UIColor.black
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white]
    }
    
    private func scanQRCode(){
        if !session.canAddInput(input) {
            return
        }
        
        if !session.canAddOutput(output) {
            return
        }
        session.addInput(input)
        session.addOutput(output)

         // 添加预览图层
        preview.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: view.frame.height)
        view.layer.insertSublayer(preview, at: 0)
        preview.videoGravity = AVLayerVideoGravity.resize

        output.metadataObjectTypes = output.availableMetadataObjectTypes
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        session.startRunning()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        

        NotificationCenter.default.addObserver(self, selector: #selector(startAnimation), name: UIApplication.didBecomeActiveNotification, object: nil)
        
        startAnimation()
    }
    
    @objc private func startAnimation(){
        scanLineTop.constant = -containerHeight.constant
        view.layoutIfNeeded()
        
        UIView.animate(withDuration: 1.0) {
            UIView.setAnimationRepeatCount(MAXFLOAT)

            self.scanLineTop.constant = self.containerHeight.constant
            self.view.layoutIfNeeded()
        }
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        navigationController?.navigationBar.barTintColor = UIColor.white
        navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.black]
    }
    
    @objc private func rightBtnClick(){
        
    }
    
    ///输入对象
    private lazy var input: AVCaptureDeviceInput = {
        let device = AVCaptureDevice.default(for: .video)
        return try! AVCaptureDeviceInput(device: device!)
    }()
    ///会话
    private lazy var session: AVCaptureSession = AVCaptureSession()
    ///输出对象
    private lazy var output: AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    ///预览图层
    private lazy var preview: AVCaptureVideoPreviewLayer = AVCaptureVideoPreviewLayer(session: self.session)

}

extension QRCodeViewCtr: AVCaptureMetadataOutputObjectsDelegate{
    
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        let metadata = metadataObjects.last as? AVMetadataMachineReadableCodeObject

        NSLog(message: metadata?.stringValue)
    }
    
}
